package com.njcb.ams.util;


import com.google.common.collect.Lists;
import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.support.exception.ExceptionCode;
import com.njcb.ams.support.exception.ExceptionUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

/**
 * @author liuyanlong
 */
@Component
public class AmsValidateUtils {
    @Resource
    private Validator validator;

    public static AmsValidateUtils getInstance() {
        return AppContext.getBean(AmsValidateUtils.class);
    }

    public static void validate(Object param) {
        getInstance().validateParam(param);
    }

    private void validateParam(Object param) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(param);
        List<String> messages = Lists.newArrayList();
        for (ConstraintViolation<Object> error : constraintViolations) {
            messages.add(error.getMessage() + "[" + error.getPropertyPath() + "]");
        }
        if (!messages.isEmpty()) {
            ExceptionUtil.throwAppException(AmsJsonUtils.objectToJson(messages), ExceptionCode.PARAM_VALIDATE_FAIL);
        }
    }
}
